package com.ctsi.canal.starter.util;

import com.ctsi.canal.starter.config.annotation.CanalColumn;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author ajh
 * @date 2019/10/24 15:24
 */
public class EntryUtil {

    private static final Map<Class<?>, Map<String, String>> CACHE = new ConcurrentHashMap<>();


    /**
     * 获取字段名称和实体属性的对应关系
     *
     * @param c class
     * @return map
     */
    public static Map<String, String> getFieldName(Class<?> c) {
        Map<String, String> map = CACHE.get(c);
        if (map == null) {
            List<Field> fields = FieldUtils.getAllFieldsList(c);
            //如果实体类中存在column 注解，则使用column注解的名称为字段名
            map = fields.stream()
                    .filter(field -> !Modifier.isStatic(field.getModifiers()))
                    .collect(Collectors.toMap(EntryUtil::getColumnName, Field::getName));
            CACHE.putIfAbsent(c, map);
        }
        return map;
    }


    private static String getColumnName(Field field) {
        CanalColumn annotation = field.getAnnotation(CanalColumn.class);
        if (annotation != null) {
            return annotation.name();
        } else {
            return field.getName();
        }
    }


}
